package com.minisoft.workhour.parser;

import com.minisoft.workhour.model.WorkItem;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 周报Excel解析器
 */
@Slf4j
public class WeeklyReportParser {

    // 日期范围格式：2025.06.02-2025.06.08
    private static final Pattern DATE_RANGE_PATTERN = Pattern.compile("(\\d{4}\\.\\d{2}\\.\\d{2})-(\\d{4}\\.\\d{2}\\.\\d{2})");

    // 工作项格式：序号、工作项--花费工时--任务编号
    private static final Pattern WORK_ITEM_PATTERN = Pattern.compile("\\d+、(.+?)--([\\d.]+)小时--([A-Za-z0-9]+)");

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy.MM.dd");
    
    /**
     * 解析Excel文件
     */
    public List<WorkItem> parseExcel(String filePath) throws IOException {
        List<WorkItem> workItems = new ArrayList<>();
        
        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = new XSSFWorkbook(fis)) {
            
            // 遍历所有sheet
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i);
                String sheetName = sheet.getSheetName();
                
                log.info("处理Sheet: {}", sheetName);
                
                // 解析日期范围
                LocalDate[] dateRange = parseDateRange(sheetName);
                if (dateRange == null) {
                    log.warn("Sheet名称格式不正确，跳过: {}", sheetName);
                    continue;
                }
                
                // 解析工作项（C11-C17）
                List<WorkItem> sheetWorkItems = parseWorkItems(sheet, dateRange);
                workItems.addAll(sheetWorkItems);
            }
        }
        
        log.info("总共解析出 {} 个工作项", workItems.size());
        return workItems;
    }
    
    /**
     * 解析日期范围
     */
    private LocalDate[] parseDateRange(String sheetName) {
        Matcher matcher = DATE_RANGE_PATTERN.matcher(sheetName);
        if (!matcher.find()) {
            return null;
        }
        
        try {
            LocalDate startDate = LocalDate.parse(matcher.group(1), DATE_FORMATTER);
            LocalDate endDate = LocalDate.parse(matcher.group(2), DATE_FORMATTER);
            return new LocalDate[]{startDate, endDate};
        } catch (Exception e) {
            log.error("解析日期范围失败: {}", sheetName, e);
            return null;
        }
    }
    
    /**
     * 解析工作项
     */
    private List<WorkItem> parseWorkItems(Sheet sheet, LocalDate[] dateRange) {
        List<WorkItem> workItems = new ArrayList<>();
        LocalDate startDate = dateRange[0];
        
        // 解析C11-C17（行号10-16，列号2）
        for (int rowIndex = 10; rowIndex <= 16; rowIndex++) {
            Row row = sheet.getRow(rowIndex);
            if (row == null) continue;
            
            Cell cell = row.getCell(2); // C列
            if (cell == null) continue;
            
            String cellValue = getCellValueAsString(cell);
            if (cellValue == null || cellValue.trim().isEmpty()) {
                continue;
            }
            
            // 计算当前行对应的日期（C11对应第一天，C12对应第二天...）
            LocalDate workDate = startDate.plusDays(rowIndex - 10);
            
            // 解析单元格中的工作项
            List<WorkItem> cellWorkItems = parseWorkItemsFromCell(cellValue, workDate);
            workItems.addAll(cellWorkItems);
        }
        
        return workItems;
    }
    
    /**
     * 从单元格内容解析工作项
     */
    private List<WorkItem> parseWorkItemsFromCell(String cellValue, LocalDate workDate) {
        List<WorkItem> workItems = new ArrayList<>();
        
        // 按行分割
        String[] lines = cellValue.split("\\r?\\n");
        
        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty()) continue;
            
            Matcher matcher = WORK_ITEM_PATTERN.matcher(line);
            if (matcher.find()) {
                try {
                    String description = matcher.group(1).trim();
                    double hours = Double.parseDouble(matcher.group(2));
                    String taskId = matcher.group(3).trim();
                    
                    WorkItem workItem = new WorkItem(description, hours, taskId, workDate);
                    workItems.add(workItem);
                    
                    log.info("解析工作项: {}", workItem);
                } catch (NumberFormatException e) {
                    log.error("解析工时失败: {}", line, e);
                }
            } else {
                log.warn("工作项格式不正确，跳过: {}", line);
            }
        }
        
        return workItems;
    }
    
    /**
     * 获取单元格值作为字符串
     */
    private String getCellValueAsString(Cell cell) {
        if (cell == null) return null;
        
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return null;
        }
    }
}
